<?php

namespace App\Service\WorkOrder\Appraise;

use App\Models\Appraise\AppraiseMessageTaskModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\System\SystemNotifyService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class NotifyService
{
    /**
     * 发送一个 商家App评价站内信,(异步，每分钟)
     * @param string $targetId
     * @param int $type
     * @param int $userId
     * @param int $shopId
     * @param array $messageParams
     * @return void
     */
    public static function notify(string $targetId, int $type, int $userId = 0, int $shopId = 0, array $messageParams = [])
    {
        /*if ($userId < 1) {
            return;
        }*/
        if ($type < 1) {
            // type类型不正确
            return;
        }
        $config = AppraiseService::getNewConfig($type);
        if (empty($config)) {
            // 没有此类型的配置
            return;
        }
        if (($config['delaySeconds'] ?? -1) < 0) {
            // delaySeconds小于0时，则认为无需发送消息
            return;
        }
        $task           = new AppraiseMessageTaskModel;
        $task->targetId = $targetId;
        $task->type     = $type;
        $task->userId   = $userId;
        $task->shopId   = $shopId;
        $task->messageParams   = json_encode($messageParams, JSON_UNESCAPED_UNICODE);
        $task->appointmentAt   = time() + $config['delaySeconds'];
        $task->save();
    }

    /**
     * 每分钟跑的计划任务
     * @return void
     */
    public static function crontabInMinute()
    {
//        $range = [Carbon::now()->startOfMinute()->timestamp, Carbon::now()->endOfMinute()->timestamp];
        while (true) {
            DB::beginTransaction();
            $task = AppraiseMessageTaskModel::query()
                ->where('appointmentAt', '<', time())
                ->where('sendAt', 0)
                ->lock(true)
                ->first();
            if (null === $task) {
                break;
            }
            $config = AppraiseService::getNewConfig($task->type);
            if (empty($config)) {
                // 标记为异常的
                $task->sendAt = 1;
                DB::commit();
                continue;
            }
            if (!($config['switch'] ?? false)) {
                // 系统配置，此类型的消息无需推送
                $task->sendAt = 2;
                DB::commit();
                continue;
            }
            $summary = $config['messageContent'] ?? '没有配置的消息内容';
            $messageParams = json_decode($task->messageParams, true);
            if (is_array($messageParams)) {
                foreach ($messageParams as $key => $value) {
                    $summary = str_replace('{$'.$key.'}', $value, $summary);
                }
            }
            if ($task->userId) {
                $userIds = [$task->userId];
            } else {
                $userIds = array_values(
                    array_column(
                        (RmsUserRemote::getShopManagerUserByShopId([$task->shopId])['lists'] ?? []),
                        "userId"
                    )
                );
            }
            SystemNotifyService::customerBatchPush(
                $userIds,
                $config['messageTitle'] ?? '您有一条新消息',
                $summary,
                config('webUrl.notify_web_cdn_url') . '#/pages/work-order/appraise/appraise?hideAppBar=true&' . http_build_query([
                    'id'   => $task->targetId,
                    'type' => $task->type,
                ]),
                $task->shopId,
                SystemNotifyCenterModel::NOTIFY_TYPE_3,
                SystemNotifyCenterModel::NOTIFY_TARGET_1,
                '',
                SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
                '',
                SystemNotifyCenterModel::IS_POPUP_ON,
                1,
                '创建消息',
                ['path' => 'kuafoodmerchantapp://messageCenter']
            );
            $task->sendAt = time();
            $task->save();
            DB::commit();
        }
    }
}
